<template>
  <div style="margin-top: 20px">
    <ko-card :title="$t('business.configuration.certificate')">
      <el-form ref="form" label-position="top" :model="editForm" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              :label="$t('business.configuration.privateKey')"
              prop="crt"
            >
              <ko-data-item
                v-model="editForm.key"
                class="w-full"
                itemType="textarea"
                :rows="5"
                @change="syncToModel"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('business.configuration.certificate')"
              prop="key"
            >
              <ko-data-item
                v-model="editForm.crt"
                class="w-full"
                itemType="textarea"
                :rows="5"
                @change="syncToModel"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </ko-card>
  </div>
</template>

<script setup lang="ts">
import KoCard from "@/views/domain/kubeHud/views/components/ko-card/index.vue";
import KoDataItem from "@/views/domain/kubeHud/views/components/ko-data-item/index.vue";
// import Rules from "@/views/domain/kubeHud/utils/rules";
import { onMounted, ref } from "vue";
import { useFormRule } from "../../../utils/rules";
import { decodeFromBase64, encodeToBase64 } from "@/utils/text";
const { RequiredRule } = useFormRule();

type Prop = {
  certificateObj: any;
};

const props = defineProps<Prop>();
const emit = defineEmits(["update:certificateObj"]);
const editForm = ref({
  crt: "",
  key: ""
});

const rules = {
  key: [RequiredRule]
};

const parseToForm = () => {
  editForm.value.crt = decodeFromBase64(props.certificateObj["tls.crt"] ?? "");

  editForm.value.key = decodeFromBase64(props.certificateObj["tls.key"] ?? "");
};

const syncToModel = () => {
  const result = {
    "tls.crt": encodeToBase64(editForm.value.crt),
    "tls.key": encodeToBase64(editForm.value.key)
  };
  emit("update:certificateObj", result);
};

onMounted(() => {
  parseToForm();
});
</script>

<style scoped></style>
